package com.shenxuchen.crm.service;

import com.shenxuchen.crm.constant.Constants;
import com.shenxuchen.crm.exception.CRMException;
import com.shenxuchen.crm.mapper.DeptMapper;
import com.shenxuchen.crm.mapper.UserMapper;
import com.shenxuchen.crm.pojo.Dept;
import com.shenxuchen.crm.pojo.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private DeptMapper deptMapper;

    // 从配置文件读取配置
    @Value("${salt}")
    private String salt;

    public User login(String username, String password, String userIP) {
        // 密码加密处理
        // 常用的加密方式：MD5加密、SHA-1、SHA-256
        // 简单的使用MD5等算法，还是能够通过“碰撞”来进行破解，不够安全！
        //password = DigestUtils.md5DigestAsHex(password.getBytes());
        // 加盐处理：系统帮助用户在密码之前增加一个随机的字符串(盐)，然后再进行加密
        password = DigestUtils.md5DigestAsHex((salt + password).getBytes());

        User user = userMapper.login(username, password);

        String errMsg = checkUser(user, userIP);
        if (errMsg == null) {



            return user;
        }

        throw new CRMException(errMsg);
    }

    private String checkUser(User user, String userIP) {
        if (user == null) {
            return Constants.MSG.ERR_USERNAME_OR_PWD;
        }

        // 是否失效,失效时间为空表示永不失效
        if (StringUtils.hasText(user.getExpireTime())) {
            // expireTime: yyyy-MM-dd HH:mm:ss
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                // 2020
                Date expireTime = Constants.SDF19.parse(user.getExpireTime());
                // 2021
                Date now = new Date();
                if (now.after(expireTime)) {
                    return Constants.MSG.ACCOUNT_EX;
                }
            } catch (ParseException e) {
                e.printStackTrace();
                return Constants.MSG.ACCOUNT_EX;
            }
        }

        //是否锁定: 0表示锁定 1表示启用
        if (!"1".equals(user.getLockStatus())) {
            return Constants.MSG.ACCOUNT_LOCK;
        }

        //IP是否允许访问:为空时表示不限制IP，多个IP地址之间使用半角逗号隔开
        if (StringUtils.hasText(user.getAllowIps())) {
            // 127.0.0.1,192.168.137.1
            String[] ips = user.getAllowIps().split(",");
            boolean allow = false; // 是否允许
            for (String ip : ips) {
                if (ip.equals(userIP)) {
                    allow = true;
                    break;
                }
            }
            if (!allow) {
                return Constants.MSG.IP_NOT_ALLOW;
            }
        }

        Dept dept = deptMapper.getById(user.getDeptId());
        user.setDept(dept);

        return null;
    }

    public User autoLogin(String username, String password, String userIP) {
        User user = userMapper.login(username, password);

        String errMsg = checkUser(user, userIP);
        if (errMsg == null) {
            return user;
        }

        return null;
    }

    public void changePwd(String id, String oldPwd, String newPwd) {
        // 查询用户的最新信息
        User user = userMapper.getById(id);
        // 加密处理
        oldPwd = DigestUtils.md5DigestAsHex((salt + oldPwd).getBytes());
        if (!user.getLoginPwd().equals(oldPwd)) {
            throw new CRMException("原密码不正确！");
        }

        newPwd = DigestUtils.md5DigestAsHex((salt + newPwd).getBytes());
        userMapper.changePwd(id, newPwd);
    }

    public void save(User user) {
        userMapper.save(user);
    }

    public List getOwners() {
        return userMapper.getOwners();
    }
}
